package com.honeyms.project.blog.open.controller;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.honeyms.common.constant.ShiroConstants;
import com.honeyms.common.utils.R;
import com.honeyms.common.utils.ServletUtils;
import com.honeyms.framework.web.controller.BaseController;
import com.honeyms.framework.web.page.BlogPageDomain;
import com.honeyms.framework.web.page.TableDataInfo;
import com.honeyms.project.blog.blogcomment.domain.BlogComment;
import com.honeyms.project.blog.blogcomment.domain.BlogCommentOpen;
import com.honeyms.project.blog.blogcomment.service.IBlogCommentService;
import com.honeyms.project.blog.blogcontent.domain.BlogContent;
import com.honeyms.project.blog.blogcontent.service.IBlogContentService;
import com.honeyms.project.blog.blogcontentdetail.domain.BlogContentDetail;
import com.honeyms.project.blog.blogcontentdetail.service.IBlogContentDetailService;
import com.honeyms.project.blog.blogfavoritesusercontent.domain.BlogFavoritesUserContent;
import com.honeyms.project.blog.blogfavoritesusercontent.service.IBlogFavoritesUserContentService;
import com.honeyms.project.blog.blogrecommend.domain.BlogRecommend;
import com.honeyms.project.blog.blogrecommend.service.IBlogRecommendService;
import com.honeyms.project.blog.blogzanusercontent.domain.BlogZanUserContent;
import com.honeyms.project.blog.blogzanusercontent.service.IBlogZanUserContentService;
import com.honeyms.project.system.file.domain.File;
import com.honeyms.project.system.file.service.IFileService;
import com.honeyms.project.system.user.domain.User;
import com.honeyms.project.system.user.service.IUserService;
import com.honeyms.project.system.userdetail.domain.UserDetail;
import com.honeyms.project.system.userdetail.service.IUserDetailService;
import com.honeyms.project.blog.userfans.domain.UserFans;
import com.honeyms.project.blog.userfans.service.IUserFansService;

/**
 * 无需认证直接访问
 * @author honey
 * @version 创建时间：2020年10月12日 下午2:55:54
 */
@RequestMapping("/blog/open")
@Controller
public class BlogOpenController extends BaseController 
{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
    private IBlogContentService blogContentService;
	
	@Autowired
	private IBlogContentDetailService blogContentDetailService;
	
    @Autowired
    private IBlogZanUserContentService blogZanUserContentService;
    
    @Autowired
    private IBlogFavoritesUserContentService blogFavoritesUserContentService;

    @Autowired
    private IBlogCommentService blogCommentService;

	@Autowired
	private IUserService userService;
	
	@Autowired
	private IUserDetailService userDetailService;
	
    @Autowired
    private IUserFansService userFansService;
    
    @Autowired
    private IFileService fileService;
    
    @Autowired
    private IBlogRecommendService blogRecommendService;
    
    /**
     * 查询帖子展示
     */
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo bloglist(BlogPageDomain blogPageDomain)
    {
    	BlogContent blogContent = new BlogContent();
    	if (blogPageDomain.getObjColumn()!=null || "".equals(blogPageDomain.getObjColumn())) {
			blogContent.setTitle(blogPageDomain.getObjColumn());
		}
    	blogContent.setStatus(1);
    	blogContent.setType(2);
    	startPage(blogPageDomain.getPageNum(),blogPageDomain.getPageSize());
    	List<BlogContent> list = blogContentService.selectBlogContent(blogContent);
    	return getDataTable(list);
    }
    
    /**
     * 随机查询帖子展示
     */
    @GetMapping("/listbyrand")
    @ResponseBody
    public TableDataInfo blogbyrand(BlogPageDomain blogPageDomain)
    {
    	BlogContent blogContent = new BlogContent();
    	if (blogPageDomain.getObjColumn()!=null && "".equals(blogPageDomain.getObjColumn())) {
    		blogContent.setTitle(blogPageDomain.getObjColumn());
    	}
    	blogContent.setStatus(1);
    	blogContent.setType(2);
    	startPage(blogPageDomain.getPageNum(),blogPageDomain.getPageSize());
    	List<BlogContent> list = blogContentService.selectBlogContentListByRand(blogContent);
    	return getDataTable(list);
    }
	
    /**
     * 打开帖子
     * @param contentId
     * @param mmap
     * @return
     */
	@GetMapping("/post/{objid}")
	public String post(@PathVariable("objid") String contentId, ModelMap mmap){
		//验证传的字符是否为数字
		if (!Pattern.compile("^[-\\+]?[\\d]*$").matcher(contentId).matches()) {
			return "error/404";
		}
		Long cid=Long.parseLong(contentId);
		//id为10以下的为系统配置不允许访问
		if (cid<10) {
			return "error/404";
		}
		BlogContent blog = blogContentService.selectBlogContentById(cid);
		if (blog==null) {
			return "error/404";
		}
		mmap.put("content", blog);
		if (getSysUser()!=null) {
			BlogZanUserContent blogZanUserContent = new BlogZanUserContent();
			blogZanUserContent.setUserId(getUserId());
			blogZanUserContent.setContentId(cid);
			BlogFavoritesUserContent blogFavoritesUserContent = new BlogFavoritesUserContent();
			blogFavoritesUserContent.setUserId(getUserId());
			blogFavoritesUserContent.setContentId(cid);
			mmap.put("iszan", blogZanUserContentService.selectBlogZanUserContentList(blogZanUserContent).isEmpty());
			mmap.put("isfavorites", blogFavoritesUserContentService.selectBlogFavoritesUserContentList(blogFavoritesUserContent).isEmpty());
			mmap.put("user", getSysUser());
			
			//智能统计
			BlogRecommend blogRecommend = new BlogRecommend();
			blogRecommend.setUserId(getUserId());
			blogRecommend.setTags(blog.getTags());
			List<BlogRecommend> blogRecommends = blogRecommendService.selectBlogRecommendList(blogRecommend);
			if (blogRecommends.isEmpty()) {
				blogRecommend.setCount(1L);
				blogRecommendService.insertBlogRecommend(blogRecommend);
			}else {
				blogRecommend=blogRecommends.get(0);
				blogRecommend.setCount(blogRecommend.getCount()+1);
				blogRecommendService.updateBlogRecommend(blogRecommend);
			}
		}
		//帖子点击量加1
		BlogContentDetail blogContentDetail = blogContentDetailService.selectBlogContentDetailById(cid);
		blogContentDetail.setViews(blogContentDetail.getViews()+1);
		blogContentDetailService.updateBlogContentDetail(blogContentDetail);
		mmap.put("contentdetail", blogContentDetail);
		//随机推荐
		BlogContent blogContent = new BlogContent();
    	blogContent.setStatus(2);
    	blogContent.setType(2);
		startPage(1,6);
		List<BlogContent> randContent = blogContentService.selectBlogContentListByRand(blogContent);
		mmap.put("randContent", randContent);
		return "blog/index/post";
	}
	
    /**
     * 查询评论详情列表
     */
    @GetMapping("/listcomment")
    @ResponseBody
    public TableDataInfo commentlist(BlogPageDomain blogPageDomain)
    {
    	blogPageDomain.setOrderByColumn("a.comment_id");
    	blogPageDomain.setIsAsc("desc");
    	BlogCommentOpen blogCommentOpen = new BlogCommentOpen();
    	if (!StringUtils.isEmpty(blogPageDomain.getObjColumn())) {
    		blogCommentOpen.setContentId(Long.parseLong(blogPageDomain.getObjColumn()));
		}
    	startPage(blogPageDomain.getPageNum(),blogPageDomain.getPageSize(),blogPageDomain.getOrderBy());
    	List<BlogCommentOpen> list = blogCommentService.selectBlogCommentOpenList(blogCommentOpen);
    	for (BlogCommentOpen blogComment : list) {
			if ("".equals(blogComment.getAvatar())) {
				blogComment.setAvatar("/img/logo/honey-b.png");
			}
			if ("".equals(blogComment.getPavatar())) {
				blogComment.setPavatar("/img/logo/honey-b.png");
			}
		}
    	return getDataTable(list);
    }

    /**
     * 查看ta人主页
     * @param uId
     * @param mmap
     * @return
     */
  	@GetMapping("/otherpersonalmain/{objid}")
  	public String otherpersonalmain(@PathVariable("objid") String uId,ModelMap mmap) {
  		//验证传的字符是否为数字
		if (!Pattern.compile("^[-\\+]?[\\d]*$").matcher(uId).matches()) {
			return "error/404";
		}
		Long userId=Long.parseLong(uId);
  		if (getSysUser()!=null) {
  			UserFans userFans = new UserFans();
  			userFans.setUserId(userId);
  			userFans.setFansId(getUserId());
  			mmap.put("isfans", userFansService.selectUserFansList(userFans).isEmpty());
			mmap.put("user", getSysUser());
		}
  		User user = userService.selectUserById(userId);
  		if (user==null) {
			return "error/404";
		}
  		mmap.put("others", user);
  		UserDetail userDetail = userDetailService.selectUserDetailById(userId);
  		if (getSysUser()!=null) {
  			if (userId!=getUserId()) {
  	  	  		userDetail.setVisits(userDetail.getVisits()+1);
  	  	  		userDetailService.updateUserDetail(userDetail);
  			}
		}
  		mmap.put("userdetail", userDetail);
  		return "blog/index/otherpersonalmain";
  	}
  	
  	/**
  	 * ta人主页帖子展示
  	 * @param blogPageDomain
  	 * @return
  	 */
  	@GetMapping("/otherlist")
  	@ResponseBody
  	public TableDataInfo otherlist(BlogPageDomain blogPageDomain) {
  		BlogContent blogContent = new BlogContent();
    	if (blogPageDomain.getObjColumn()!=null) {
    		Long userId = Long.parseLong(blogPageDomain.getObjColumn());
			blogContent.setCreatedId(userId);
		}
    	blogContent.setStatus(2);
    	blogContent.setType(2);
    	startPage(blogPageDomain.getPageNum(),blogPageDomain.getPageSize());
  		List<BlogContent> list = blogContentService.selectBlogContent(blogContent);
  		return getDataTable(list);
  	}

    /**
	 * 游客留言
	 */
	@ResponseBody
	@PostMapping("/savevisitor")
	public R savevisitor(BlogComment comment,String validateCode,HttpServletRequest request) {
        /*if (!ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).equals(validateCode)){
            return error(1,"验证码错误");
        }
        // 验证码清除，防止多次使用。
        request.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);*/
		if (!StringUtils.isEmpty(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA)))
        {
			return error(1,"验证码错误");
        }
		if (comment.getContent().contains("<")||comment.getContent().contains(">")||comment.getContent().contains("href")||comment.getContent().contains("src")) {
			logger.info("游客留言： 用户名=>游客;   留言内容=> {}   返回:评论中存在非法字符!",comment.getContent());
			return error(1,"评论中存在非法字符!");
		}
		//设置评论者id
		comment.setUserId(114L);
		comment.setCreateDate(new Date());
		if (comment.getContent().length()<100&&comment.getContent().length()>0) {
			if(blogCommentService.insertBlogComment(comment)>0){
				logger.info("游客留言： 用户名=>游客;   留言内容=> {}   返回:留言成功！",comment.getContent());
				return ok(0,"留言成功！");
			}
		} else if(comment.getContent().length()==0||comment.getContent().equals("")){
			  logger.info("游客留言： 用户名=>游客;   留言内容=> {}   返回:留言不允许为空！",comment.getContent());
              return error(1,"留言不允许为空,请说点什么吧！");
		}else {
			  logger.info("游客留言： 用户名=>游客;   留言内容=> {}   返回:留言内容不合法（内容过长），请修改后再发送！！",comment.getContent());
			  return error(1,"留言内容不合法（内容过长），请修改后再发送！");
		}
		return error(1,"未知异常请联系管理员！");
	}
	
	//去站长相册
	@GetMapping("/zzalbom")
	public String zzalbom(ModelMap mmap) {
		mmap.put("user", userService.selectUserById(1L));
		return "blog/index/albom";
	}
	
	//去用户相册
	@GetMapping("/albom/{userId}")
	public String albom(@PathVariable("userId") String userId,ModelMap mmap) {
		if (!Pattern.compile("^[-\\+]?[\\d]*$").matcher(userId).matches()) {
			return "error/404";
		}
		Long id=Long.parseLong(userId);
		mmap.put("user", userService.selectUserById(id));
		return "blog/index/albom";
	}
	
	@PostMapping("/albom")
	@ResponseBody
	public TableDataInfo albom(BlogPageDomain blogPageDomain) {
		File file = new File(); 
		file.setUserId(Long.parseLong(blogPageDomain.getObjColumn()));
		file.setIspub("1");
    	startPage(blogPageDomain.getPageNum(),blogPageDomain.getPageSize());
    	List<File> list = fileService.selectFileList(file);
		return getDataTable(list);
	}
}
